
#include <BHBoxLayout>
#include <BTableItem>
#include <BListItem>
#include <BLineEdit>
#include <BClass>

#include "StringUtils.h"
#include "ScriptFormat.h"
#include "InvokeBoard.h"

InvokeBoard::InvokeBoard(BWidget* parent) : BWidget(parent)
{
	_scrollToLastRow = false;

	_callWidget = new BTableWidget();
	_callWidget->setColumnCount(2);
	_callWidget->setColumnLabel(0, "type");
	_callWidget->setColumnLabel(1, "name");
	_callWidget->setColumnWidth(0, 200);
	_callWidget->setColumnWidth(1, 200);
	_callWidget->setColumnPolicy(Policy_Preferred | Policy_Expanding);
	_callWidget->setGridStyle(Grid_Crossing);
	BLayout* layout = new BLayout(this);
	layout->setWidget(_callWidget);

	connect(_callWidget, Signal_Fresh, &InvokeBoard::slotStackFreshed);
}
InvokeBoard::~InvokeBoard()
{

}

void InvokeBoard::setScript(BScript* script)
{
	_script = script;
}
BScript* InvokeBoard::script() const
{
	return _script;
}

void InvokeBoard::freshStack(const BVariantArray& stack)
{
	_callWidget->clearItems();
	for (int i = 0; i < stack.size(); i++)
	{
		const BVariant& var = stack(i);
		if (var.type() == "call")
		{
			int row = _callWidget->addRows();
			_callWidget->setRowAsset(row, var.value());
			_callWidget->setItem(row, 0, var.type());
			_callWidget->setItem(row, 1, var.name());
			if (BTableItem* item = _callWidget->item(row, 1))
			{
				ScriptFormat* format = new ScriptFormat();
				format->setScript(_script);
				format->update(item->text());
				item->setFormat(format);
			}
		}
	}
	_scrollToLastRow = true;
}

void InvokeBoard::slotStackFreshed(BObject* object)
{
	if (_scrollToLastRow)
	{
		int lastRow = _callWidget->rowCount() - 1;
		BTableItem* item = _callWidget->item(lastRow, 0);
		_callWidget->scrollToItem(item);
		_scrollToLastRow = false;
	}
}
